package cn.stylefeng.guns.modular.robot;

import cn.stylefeng.guns.modular.robot.cmd.impl.MgrCmdBiz;
import cn.stylefeng.guns.modular.robot.utils.RobotUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;

import javax.annotation.Resource;

@Slf4j
@Component
public class Zhzfbot extends TelegramLongPollingBot {

    @Value("${telegram.bot.username}")
    private String botUsername;

    @Resource
    private MgrCmdBiz mgrCmdBiz;

    private Zhzfbot(@Value("${telegram.bot.token}") String botToken) {
        super(botToken);
    }

    @Override
    public void onUpdateReceived(Update update) {
        try {
            if(StringUtils.isNotBlank(update.getMessage().getText())){
                log.info("群消息发送：群名称：" + update.getMessage().getChat().getTitle() + "，发送人：" + update.getMessage().getFrom().getUserName() + "，群消息内容:" + update.getMessage().getText());
            }
            if (StringUtils.isBlank(update.getMessage().getText()) && !CollectionUtils.isEmpty(update.getMessage().getNewChatMembers()) && update.getMessage().getNewChatMembers().get(0).getIsBot()
                    && update.getMessage().getNewChatMembers().get(0).getUserName().equals(getBotUsername())) {
                RobotUtils.sendText(update.getMessage().getChatId(), "感谢您把我加入到群内。\n接下来由权限人输入 ** 激活本群\n输入 \"指令查询\" 获取帮助", this);
                return;
            }
            mgrCmdBiz.handle(update, this);
        }catch (Exception e){
            log.error("业务异常，请处理：",e);
        }
    }

    @Override
    public String getBotUsername() {
        return botUsername;
    }

}
